package com.springbootsecuritydemo.filter;

import com.springbootsecuritydemo.entity.LoginUser;
import com.springbootsecuritydemo.utils.JwtUtil;
import com.springbootsecuritydemo.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Token验证器
 *
 * @author Daft_V
 * @date 2022/4/13 14:38
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Value("{jwt.salt}")
    String salt;
    @Autowired
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //将httpServletRequest、httpServletResponse传到下一个过滤器
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //解析token
        String uid;
        try {
            Claims claims = JwtUtil.parseJWT(salt, token);
            uid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中解析用户信息
        LoginUser loginUser = redisCache.getCacheObject("login:"+uid);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行到下一个过滤器
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
